package com.aizhixin.lab.course.course.service;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.course.course.domain.ContainerExperimentInfoDomain;
import com.aizhixin.lab.course.course.domain.CourseChapterDomain;
import com.aizhixin.lab.course.course.domain.CourseChapterFileDomain;
import com.aizhixin.lab.course.course.domain.CourseChapterNameDomain;
import com.aizhixin.lab.course.course.dto.*;
import com.aizhixin.lab.course.course.entity.Course;
import com.aizhixin.lab.course.course.entity.CourseChapter;
import com.aizhixin.lab.course.course.entity.CourseChapterAtt;
import com.aizhixin.lab.course.course.entity.CourseChapterFile;
import com.aizhixin.lab.course.course.repository.*;

import com.aizhixin.lab.docker.domain.ChapterImagesDomain;
import com.aizhixin.lab.docker.service.ChapterImagesService;
import com.aizhixin.lab.project.course.uilt.NumToChinese;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@Slf4j
@Service
@Transactional
public class TeacherChapterService {
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private CourseChapterRepository chapterRepository;
    @Autowired
    private CourseChapterFileRepository chapterFileRepository;
    @Autowired
    private CourseChapterAttRepository attRepository;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;
    @Autowired
    private ChapterImagesService chapterImagesService;
    @Autowired
    private CourseChapterLikeRepository chapterLikeRepository;


    public List<CourseChapter> getList(String courseId) {
        List<CourseChapter> list = chapterRepository.findByCourseIdAndDeleteFlagAndParentIdIsNullOrderByOrderNo(courseId, DataValidity.VALID.getState());
        return setChapter(list);
    }

    private List<CourseChapter> setChapter(List<CourseChapter> list) {
        List<CourseChapter> result = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (CourseChapter item : list) {
                if (item.getDeleteFlag().equals(DataValidity.VALID.getState())) {
                    if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                        List<CourseChapter> children = setChapter(item.getChildrens());
                        item.setChildrens(children);
                    }
                    result.add(item);
                }
            }
        }
        return result;
    }

    public CourseChapterNameDomain getChapterName(Long id) {
        CourseChapterNameDomain domain = new CourseChapterNameDomain();
        CourseChapter chapter = chapterRepository.findByIdAndDeleteFlag(id, DataValidity.VALID.getState());
        if (chapter != null) {
            domain.setName(chapter.getName());
            Course course = courseRepository.findByIdAndDeleteFlag(chapter.getCourseId(), DataValidity.VALID.getState());
            if (course != null) {
                domain.setCourseName(course.getName());
            }
        }

        return domain;
    }

    public List<CourseChapterDomain> getListWithFile(String courseId) {
        List<CourseChapter> list = chapterRepository.findByCourseIdAndDeleteFlagAndParentIdIsNullOrderByOrderNo(courseId, DataValidity.VALID.getState());
        List<CourseChapterDomain> result = setChapterDomain(list);
        return result;
    }

    public List<CourseChapterDomain> getListWithFileWithoutHide(String courseId) {
        List<CourseChapter> list = chapterRepository.findByCourseIdAndDeleteFlagAndParentIdIsNullOrderByOrderNo(courseId, DataValidity.VALID.getState());
        List<CourseChapterDomain> result = setChapterDomainWithoutHide(list);
        return result;
    }

    private List<CourseChapterDomain> setChapterDomain(List<CourseChapter> list) {
        List<CourseChapterDomain> result = new ArrayList<>();
        if (!list.isEmpty()) {
            for (CourseChapter item : list) {
                if (item.getDeleteFlag().equals(DataValidity.VALID.getState())) {
                    CourseChapterDomain d = new CourseChapterDomain();
                    BeanUtils.copyProperties(item, d);
                    d.setLikeNum(chapterLikeRepository.countByChapterId(item.getId()));
                    List<CourseChapterFile> files = chapterFileRepository.findByChapterIdAndDeleteFlagOrderByNo(item.getId(), DataValidity.VALID.getState());
                    if (!files.isEmpty()) {
                        Map<Integer, Integer> fileCountMap = new HashMap<>();
                        List<CourseChapterFileDomain> fileDomains = new ArrayList<>();
                        for (CourseChapterFile file : files) {
                            if (file.getDeleteFlag().equals(DataValidity.VALID.getState())) {
                                CourseChapterFileDomain fd = new CourseChapterFileDomain();
                                BeanUtils.copyProperties(file, fd);
                                fileDomains.add(fd);
                                Integer fileCount = fileCountMap.get(fd.getType());
                                if (fileCount == null) {
                                    fileCount = 0;
                                }
                                fileCountMap.put(fd.getType(), fileCount + 1);
                            }
                        }
                        d.setFiles(fileDomains);
                        d.setFileCounts(fileCountMap);
                    }
                    if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                        List<CourseChapterDomain> children = setChapterDomain(item.getChildrens());
                        d.setChildrens(children);
                    }
                    result.add(d);
                }
            }
        }
        return result;
    }

    private List<CourseChapterDomain> setChapterDomainWithoutHide(List<CourseChapter> list) {
        List<CourseChapterDomain> result = new ArrayList<>();
        if (!list.isEmpty()) {
            for (CourseChapter item : list) {
                if (item.getDeleteFlag().equals(DataValidity.VALID.getState()) && (item.getIsHide() == null || !item.getIsHide())) {
                    CourseChapterDomain d = new CourseChapterDomain();
                    BeanUtils.copyProperties(item, d);
                    List<CourseChapterFile> files = chapterFileRepository.findByChapterIdAndIsHideAndDeleteFlagOrderByNo(item.getId(), false, DataValidity.VALID.getState());
                    if (!files.isEmpty()) {
                        Map<Integer, Integer> fileCountMap = new HashMap<>();
                        List<CourseChapterFileDomain> fileDomains = new ArrayList<>();
                        for (CourseChapterFile file : files) {
                            if (file.getDeleteFlag().equals(DataValidity.VALID.getState()) && (file.getIsHide() == null || !file.getIsHide())) {
                                CourseChapterFileDomain fd = new CourseChapterFileDomain();
                                BeanUtils.copyProperties(file, fd);
                                fileDomains.add(fd);
                                Integer fileCount = fileCountMap.get(fd.getType());
                                if (fileCount == null) {
                                    fileCount = 0;
                                }
                                fileCountMap.put(fd.getType(), fileCount + 1);
                            }
                        }
                        d.setFiles(fileDomains);
                        d.setFileCounts(fileCountMap);
                    }
                    if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                        List<CourseChapterDomain> children = setChapterDomainWithoutHide(item.getChildrens());
                        d.setChildrens(children);
                    }
                    result.add(d);
                }
            }
        }
        return result;
    }

    public Map<String, Object> add(CourseChapterAddDTO dto,Boolean isOpenSync) {
        ChapterImagesDomain chapterImagesDomain = new ChapterImagesDomain();
        Course course = courseRepository.findCourseById(dto.getCourseId());
        CourseChapter chapter = new CourseChapter();
        BeanUtils.copyProperties(dto, chapter);
        if (chapter.getParentId() != null && chapter.getParentId() == 0) {
            chapter.setParentId(null);
        }
        chapter.setIsExp(false);
        if (!Objects.isNull(course)){
            if (course.getIsDefaultEx()==1){
                chapter.setIsExp(true);
                chapter.setVmName(course.getVmName());
                chapter.setVmNum(course.getVmNum());
            }
        }
        chapter.setIsHide(false);
        String no = chapter.getChapterNo().replaceAll("\\.", "");
        chapter.setOrderNo(Integer.parseInt(no));
        if (chapter.getParentId() == null || chapter.getParentId() == 0) {
            chapter.setChineseOrderNo(NumToChinese.numToChinese(chapter.getChapterNo()));
        }
        chapter = chapterRepository.save(chapter);
        if (chapter.getIsExp()){
            chapterImagesDomain.setCourseId(dto.getCourseId());
            chapterImagesDomain.setChapterId(chapter.getId());
            chapterImagesDomain.setImageName(chapter.getVmName());
            chapterImagesDomain.setNum(chapter.getVmNum());
            chapterImagesService.saveChapterImages(chapterImagesDomain);
        }
        updateCourseChapterCount(dto.getCourseId());
        Map<String, Object> result = new HashMap<>();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, chapter);
        if (isOpenSync) {
            if (!Objects.isNull(course)) {
                if (course.getIsPublish()) {
                    if (chapter.getParentId() != null && chapter.getParentId() == 0) {
                        if (course.getParentId()!=null) {
                            chapter.setParentId(null);
                            List<Course> courseList = courseRepository.findByParentIdAndDeleteFlag(course.getParentId(), DataValidity.VALID.getState());
                            for (Course course1 : courseList) {
                                if (course1.getId().equals(dto.getCourseId())) {
                                    continue;
                                }
                                CourseChapterAddDTO courseChapterAddDTO = new CourseChapterAddDTO();
                                BeanUtils.copyProperties(dto, courseChapterAddDTO);
                                courseChapterAddDTO.setCourseId(course1.getId());
                                add(courseChapterAddDTO, false);
                            }
                            dto.setCourseId(course.getParentId());
                            add(dto, false);
                        }
                    } else {
                        if (chapter.getTemplateId() != null) {
                            List<CourseChapter> c = chapterRepository.findByTemplateIdAndDeleteFlag(chapter.getTemplateId(), DataValidity.VALID.getState());
                            for (CourseChapter courseChapter : c) {
                                if (courseChapter.getId() == dto.getParentId()) {
                                    continue;
                                }
                                CourseChapterAddDTO courseChapterAddDTO = new CourseChapterAddDTO();
                                BeanUtils.copyProperties(dto, courseChapterAddDTO);
                                courseChapterAddDTO.setCourseId(courseChapter.getCourseId());
                                courseChapterAddDTO.setParentId(courseChapter.getId());
                                add(courseChapterAddDTO, false);
                            }
                            CourseChapter courseChapter = chapterRepository.findByIdAndDeleteFlag(dto.getParentId(), DataValidity.VALID.getState());
                            if (Objects.isNull(courseChapter)) {
                                CourseChapterAddDTO courseChapterAddDTO = new CourseChapterAddDTO();
                                BeanUtils.copyProperties(dto, courseChapterAddDTO);
                                courseChapterAddDTO.setCourseId(courseChapter.getCourseId());
                                courseChapterAddDTO.setParentId(courseChapter.getId());
                                add(courseChapterAddDTO, false);
                            }
                        }
                    }
                } else {
                    if (chapter.getParentId() != null && chapter.getParentId() == 0) {
                        chapter.setParentId(null);
                        List<Course> courseList = courseRepository.findByParentIdAndDeleteFlag(course.getId(), DataValidity.VALID.getState());
                        for (Course course1 : courseList) {

                            CourseChapterAddDTO courseChapterAddDTO = new CourseChapterAddDTO();
                            BeanUtils.copyProperties(dto, courseChapterAddDTO);
                            courseChapterAddDTO.setCourseId(course1.getId());
                            add(courseChapterAddDTO, false);
                        }
                    } else {
                        List<CourseChapter> c = chapterRepository.findByTemplateIdAndDeleteFlag(chapter.getId(), DataValidity.VALID.getState());
                        for (CourseChapter courseChapter : c) {
                            CourseChapterAddDTO courseChapterAddDTO = new CourseChapterAddDTO();
                            BeanUtils.copyProperties(dto, courseChapterAddDTO);
                            courseChapterAddDTO.setCourseId(courseChapter.getCourseId());
                            courseChapterAddDTO.setParentId(courseChapter.getId());
                            add(courseChapterAddDTO, false);
                        }
                    }
                }

            }
        }
        return result;
    }

    private void updateCourseChapterCount(String courseId) {
        Course course = courseRepository.findByIdAndDeleteFlag(courseId, DataValidity.VALID.getState());
        if (course != null) {
            List<CourseChapter> list = chapterRepository.findByCourseIdAndDeleteFlagAndParentIdIsNullOrderByOrderNo(courseId, DataValidity.VALID.getState());
            Map<String, Integer> map = setChapterCount(list);
            course.setCountChapter(map.get("countChapter"));
            course.setCountSection(map.get("countSection"));
            course.setViewCountChapter(map.get("viewCountChapter"));
            course.setViewCountSection(map.get("viewCuntSection"));
            courseRepository.save(course);
        }
    }

    private Map<String, Integer> setChapterCount(List<CourseChapter> list) {
        Integer countChapter = 0;
        Integer countSection = 0;
        Integer viewCountChapter = 0;
        Integer viewCuntSection = 0;
        if (list != null && !list.isEmpty()) {
            for (CourseChapter item : list) {
                if (item.getType()==null){
                    continue;
                }
                if (item.getDeleteFlag().equals(DataValidity.VALID.getState())) {
                    if (item.getType() == 10) {
                        countChapter++;
                    } else {
                        countSection++;
                    }
                    if (!(item.getIsHide() != null && item.getIsHide())) {
                        if (item.getType() == 10) {
                            viewCountChapter++;
                        } else {
                            viewCuntSection++;
                        }
                        if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                            Map<String, Integer> map = setChapterCount(item.getChildrens());
                            countChapter += map.get("countChapter");
                            countSection += map.get("countSection");
                            viewCountChapter += map.get("viewCountChapter");
                            viewCuntSection += map.get("viewCuntSection");
                        }
                    } else {
                        if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                            Map<String, Integer> map = setChapterCount(item.getChildrens());
                            countChapter += map.get("countChapter");
                            countSection += map.get("countSection");
                        }
                    }
                }
            }
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("countChapter",countChapter);
        map.put("countSection",countSection);
        map.put("viewCountChapter",viewCountChapter);
        map.put("viewCuntSection",viewCuntSection);
        return map;
    }

    public Map<String, Object> initChapterCount(){
        Map<String, Object> result = new HashMap<>();
        List<Course> list = courseRepository.findByDeleteFlag(DataValidity.VALID.getState());
        if(!list.isEmpty()){
            for(Course item:list){
                updateCourseChapterCount(item.getId());
            }
            result.put(ApiReturnConstants.SUCCESS, true);
        }
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }

    public Map<String, Object> save(CourseChapterDTO dto,Boolean isOpenSync) {
        Map<String, Object> result = new HashMap<>();
        CourseChapter chapter = chapterRepository.findByIdAndDeleteFlag(dto.getId(), DataValidity.VALID.getState());
        if (chapter != null) {
            BeanUtils.copyProperties(dto, chapter);
            chapterRepository.save(chapter);
            if (isOpenSync){
//                String courseId = chapter.getCourseId();
                Course courseById = courseRepository.findCourseById(chapter.getCourseId());
                if (Objects.isNull(courseById)){
                    if (courseById.getIsPublish()){
                        if (chapter.getTemplateId()!=null) {
                            List<CourseChapter> courseChapterList = chapterRepository.findByTemplateIdAndDeleteFlag(chapter.getTemplateId(), DataValidity.VALID.getState());
                            courseChapterList.forEach(item->{
                                CourseChapterDTO courseChapterDTO = new CourseChapterDTO();
                                BeanUtils.copyProperties(dto,courseChapterDTO);
                                courseChapterDTO.setId(item.getId());
                                save(courseChapterDTO,false);
                            });
                        }
                        if (chapter.getTemplateId()!=null) {
                            CourseChapter courseChapter = chapterRepository.findByIdAndDeleteFlag(chapter.getTemplateId(), DataValidity.VALID.getState());
                            if (Objects.isNull(courseChapter)) {
                                CourseChapterDTO courseChapterDTO = new CourseChapterDTO();
                                BeanUtils.copyProperties(dto, courseChapterDTO);
                                courseChapterDTO.setId(courseChapter.getId());
                                save(courseChapterDTO, false);
                            }
                        }
                    }else {
                            List<CourseChapter> courseChapterList = chapterRepository.findByTemplateIdAndDeleteFlag(chapter.getId(), DataValidity.VALID.getState());
                            courseChapterList.forEach(item->{
                                CourseChapterDTO courseChapterDTO = new CourseChapterDTO();
                                BeanUtils.copyProperties(dto,courseChapterDTO);
                                courseChapterDTO.setId(item.getId());
                                save(courseChapterDTO,false);
                            });

                    }
                }

            }
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
        }
        return result;
    }

    public Map<String, Object> saveSort(CourseChapterSortDTO dto) {
        Map<String, Object> result = new HashMap<>();
        saveChapterSort(dto.getList());
        updateCourseChapterCount(dto.getCourseId());
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }

    private void saveChapterSort(List<CourseChapterSortItemDTO> list) {
        if (list != null && !list.isEmpty()) {
            for (CourseChapterSortItemDTO item : list) {
                CourseChapter chapter = chapterRepository.findByIdAndDeleteFlag(item.getId(), DataValidity.VALID.getState());
                if (chapter != null) {
                    if (item.getParentId() == null || item.getParentId() < 1) {
                        chapter.setParentId(null);
                        chapter.setChineseOrderNo(NumToChinese.numToChinese(item.getChapterNo()));
                    } else {
                        chapter.setParentId(item.getParentId());
                    }
                    chapter.setChapterNo(item.getChapterNo());
                    String no = chapter.getChapterNo().replaceAll("\\.", "");
                    chapter.setOrderNo(Integer.parseInt(no));
                    chapterRepository.save(chapter);
                    if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                        saveChapterSort(item.getChildrens());
                    }
                }
            }
        }
    }

    public Map<String, Object> hide(Long chapterId) {
        Map<String, Object> result = new HashMap<>();
        CourseChapter chapter = chapterRepository.findByIdAndDeleteFlag(chapterId, DataValidity.VALID.getState());
        if (chapter != null) {
            boolean flag = false;
            if (chapter.getIsHide() != null) {
                flag = chapter.getIsHide();
            }
            chapter.setIsHide(!flag);
            chapterRepository.save(chapter);
            updateCourseChapterCount(chapter.getCourseId());
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
        }
        return result;
    }

    public Map<String, Object> delete(Long chapterId) {
        Map<String, Object> result = new HashMap<>();
        CourseChapter chapter = chapterRepository.findByIdAndDeleteFlag(chapterId, DataValidity.VALID.getState());
        if (chapter != null) {
            deleteByParentId(chapter.getId());
            deleteFiles(chapter.getId());
            chapterRepository.delete(chapter);
            updateChapterNo(chapter.getParentId(), chapter.getChapterNo(),chapter.getCourseId());
            updateCourseChapterCount(chapter.getCourseId());
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "没有章节信息");
        }
        return result;
    }

    private void updateChapterNo(Long parentId, String chapterNo,String courseId) {
        BigDecimal no = new BigDecimal(chapterNo);
        List<CourseChapter> chapters = chapterRepository.findByParentIdAndDeleteFlagAndCourseId(parentId, DataValidity.VALID.getState(),courseId);
        if (chapters != null && !chapters.isEmpty()) {
            List<CourseChapter> list = new ArrayList<>();
            for (CourseChapter chapter : chapters) {
                BigDecimal itemNo = new BigDecimal(chapter.getChapterNo());
                if (itemNo.compareTo(no) == 1) {
                    if (chapter.getChapterNo().indexOf(".") > 0) {
                        chapter.setChapterNo(itemNo.subtract(new BigDecimal(0.01)).setScale(2, RoundingMode.HALF_UP) + "");
                    } else {
                        chapter.setChapterNo(itemNo.subtract(new BigDecimal(1)).intValue() + "");
                        List<CourseChapter> items = chapterRepository.findByParentIdAndDeleteFlag(chapter.getId(), DataValidity.VALID.getState());
                        if (items != null && !items.isEmpty()) {
                            for (CourseChapter item : items) {
                                String noStr = item.getChapterNo();
                                String[] nos = noStr.split("\\.");
                                item.setChapterNo(chapter.getChapterNo() + "." + nos[1]);
                                list.add(item);
                            }
                        }
                    }
                    String noStr = chapter.getChapterNo().replaceAll("\\.", "");
                    chapter.setOrderNo(Integer.parseInt(noStr));
                    chapter.setChineseOrderNo(noStr);
                    list.add(chapter);
                }
            }
            if (!list.isEmpty()) {
                chapterRepository.save(list);
            }
        }
    }

    private void deleteByParentId(Long parentId) {
        List<CourseChapter> chapters = chapterRepository.findByParentIdAndDeleteFlag(parentId, DataValidity.VALID.getState());
        if (chapters != null && !chapters.isEmpty()) {
            for (CourseChapter chapter : chapters) {
                deleteByParentId(chapter.getId());
                deleteFiles(chapter.getId());
                chapter.setDeleteFlag(DataValidity.INVALID.getState());
                chapterRepository.save(chapter);
            }
        }
    }

    private void deleteFiles(Long chapterId) {
        List<CourseChapterFile> files = chapterFileRepository.findByChapterIdAndDeleteFlagOrderByNo(chapterId, DataValidity.VALID.getState());
        if (files != null) {
            for (CourseChapterFile file : files) {
                file.setDeleteFlag(DataValidity.INVALID.getState());
            }
            chapterFileRepository.save(files);
        }
    }

    public List<CourseChapterFile> getFileList(Long chapterId) {
        return chapterFileRepository.findByChapterIdAndDeleteFlagOrderByNo(chapterId, DataValidity.VALID.getState());
    }

    public List<CourseChapterFile> getFileListWithoutHide(Long chapterId) {
        return chapterFileRepository.findByChapterIdAndIsHideAndDeleteFlagOrderByNo(chapterId, false, DataValidity.VALID.getState());
    }

    public Map<String, Object> saveFile(CourseChapterFileDTO dto) {
        Map<String, Object> result = new HashMap<>();
        CourseChapterFile file = null;
        if (dto.getId() != null && dto.getId().longValue() > 0) {
            file = chapterFileRepository.findByIdAndDeleteFlag(dto.getId(), DataValidity.VALID.getState());
        }
        if (file == null) {
            file = new CourseChapterFile();
            file.setIsHide(false);
        }
        BeanUtils.copyProperties(dto, file);
        if (file.getId() == null || file.getId().longValue() < 1) {
            Integer minNo = getFileNoMin(file.getChapterId());
            file.setNo(minNo - 1);
        }

        file = chapterFileRepository.save(file);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, file);
        return result;
    }

    private Integer getFileNoMin(Long chapterId) {
        List<CourseChapterFile> list = chapterFileRepository.findByChapterIdAndDeleteFlagOrderByNo(chapterId, DataValidity.VALID.getState());
        if (list != null && !list.isEmpty()) {
            CourseChapterFile file = list.get(0);
            if (file != null && file.getNo() != null) {
                return file.getNo();
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public Map<String, Object> saveFileOrder(CourseChapterFileOrderListDTO dto) {
        Map<String, Object> result = new HashMap<>();
        if (dto != null && dto.getList() != null && !dto.getList().isEmpty()) {
            Map<Long, Integer> map = new HashMap<>();
            for (CourseChapterFileOrderDTO item : dto.getList()) {
                map.put(item.getId(), item.getNo());
            }
            List<CourseChapterFile> list = chapterFileRepository.findByChapterIdAndDeleteFlagOrderByNo(dto.getChapterId(), DataValidity.VALID.getState());
            if (!list.isEmpty()) {
                for (CourseChapterFile file : list) {
                    Integer no = map.get(file.getId());
                    if (no != null) {
                        file.setNo(no);
                    }
                }
                chapterFileRepository.save(list);
            }
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
        }
        return result;
    }

    public Map<String, Object> deleteFile(Long fileId) {
        Map<String, Object> result = new HashMap<>();
        CourseChapterFile file = chapterFileRepository.findByIdAndDeleteFlag(fileId, DataValidity.VALID.getState());
        if (file != null) {
            file.setDeleteFlag(DataValidity.INVALID.getState());
            chapterFileRepository.save(file);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "没有文件信息");
        }
        return result;
    }

    public Map<String, Object> hideFile(Long chapterId) {
        Map<String, Object> result = new HashMap<>();
        CourseChapterFile file = chapterFileRepository.findByIdAndDeleteFlag(chapterId, DataValidity.VALID.getState());
        if (file != null) {
            boolean flag = false;
            if (file.getIsHide() != null) {
                flag = file.getIsHide();
            }
            file.setIsHide(!flag);
            chapterFileRepository.save(file);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
        }
        return result;
    }

    public List<CourseChapter> findCourseChapterForVm(String courseId) {
        return chapterRepository.findAllByCourseIdAndDeleteFlagAndVmNameIsNotNull(courseId, DataValidity.VALID.getState());
    }

    public List<CourseChapterAtt> getAttList(Long chapterId, Integer type) {
        return attRepository.findByChapterIdAndTypeAndDeleteFlagOrderByNo(chapterId, type, DataValidity.VALID.getState());
    }

    public Map<String, Object> saveAtt(CourseChapterAttDTO dto) {
        CourseChapterAtt att = new CourseChapterAtt();
        BeanUtils.copyProperties(dto, att);
        Integer minNo = getAttNoMin(att.getChapterId());
        att.setNo(minNo - 1);
        att = attRepository.save(att);
        Map<String, Object> result = new HashMap<>();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, att);
        return result;
    }

    private Integer getAttNoMin(Long chapterId) {
        List<CourseChapterAtt> list = attRepository.findByChapterIdAndDeleteFlagOrderByNo(chapterId, DataValidity.VALID.getState());
        if (list != null && !list.isEmpty()) {
            CourseChapterAtt file = list.get(0);
            if (file != null && file.getNo() != null) {
                return file.getNo();
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public Map<String, Object> deleteAtt(Long attId) {
        Map<String, Object> result = new HashMap<>();
        CourseChapterAtt att = attRepository.findByIdAndDeleteFlag(attId, DataValidity.VALID.getState());
        if (att != null) {
            att.setDeleteFlag(DataValidity.INVALID.getState());
            attRepository.save(att);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "没有文件信息");
        }
        return result;
    }
    RowMapper<ContainerExperimentInfoDomain> rm2 = new RowMapper<ContainerExperimentInfoDomain>() {

        @Override
        public ContainerExperimentInfoDomain mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            ContainerExperimentInfoDomain domain = new ContainerExperimentInfoDomain();
            domain.setChapterId(rs.getLong("chapter_id"));
            domain.setCourseId(rs.getString("course_id"));
            domain.setChapterName(rs.getString("chapter_name"));
            domain.setCourseName(rs.getString("course_name"));
            domain.setNum(rs.getInt("vm_num"));
            domain.setImageName(rs.getString("image_name"));
            domain.setChapterNo(rs.getLong("chapter_no"));
            return domain;
        }
    };
    public ContainerExperimentInfoDomain getExperimentInfo(Long chapterId){
        String sql="SELECT cc.id course_id,cc.`name` course_name, ccc.id chapter_id,ccc.chapter_no chapter_no,ccc.`name` chapter_name,ccc.vm_name image_name,ccc.vm_num vm_num FROM c_course_chapter ccc LEFT JOIN c_course cc ON ccc.course_id=cc.id where ccc.id="+chapterId;
        List<ContainerExperimentInfoDomain> info = pageJdbcUtil.getInfo(sql, rm2);
        if (info.size()>0){
            return info.get(0);
        }else {
            return null;
        }
    }
}
